import socket
import datetime
import logs

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口:
s.bind(('127.0.0.1', 8849))

print('绑定UDP接套字在8849端口成功！')

while True:
    # 接收数据:
    try:
        data, addr = s.recvfrom(1024)
        print("[{}] {}".format(addr, data.decode("utf-8")))
        datafile = open("./data.txt", "w+")
        timefile = open("./time.txt", "w+")
        now = datetime.datetime.now().timestamp()
        timefile.write(str(now))
        datafile.write(data.decode("utf-8"))
        logs.addLog("收到数据", addr, data.decode("utf-8"))
        # print('Received from %s:%s.' % addr % data.decode("utf-8"))
        # reply = 'Hello, %s!' % data.decode('utf-8')
        # s.sendto(reply.encode('utf-8'), addr)
    except:
        logs.addLog("接收端退出")
        print("接收端退出")
